import json
import os
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app.models import *
from app.url import *


@csrf_exempt
def upload_image(request):
    print('---------------------------------------')
    if request.method == 'POST':
        file = request.FILES['file']
        file_name = file.name
        file_path = os.path.join(settings.MEDIA_ROOT, 'upload/' + file_name)
        print(file_path, "----------------------------------")
        with open(file_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        return JsonResponse(
            {'code': 200,
             'data': {'status': 'success',
                      'imageUrl': settings.MEDIA_URL + 'upload/' + file_name,
                      'fileUrl': get_server_url(request)
                      }})
    return JsonResponse({'status': 'error', 'message': '保存失败！'})


@csrf_exempt
def save_post(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user_id = data.get('user_id', '')
        content = data.get('content', '')
        images = data.get('images', [])
        user = User.objects.get(id=user_id)
        UserBlog.objects.create(user=user, content=content, image_paths=images)
        return JsonResponse({'code': 200, 'status': 'success', 'msg': '保存成功!'})
    return JsonResponse({'code': 405, 'status': 'error', 'message': '保存失败！'})
